package com.example.login.vm

import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.GsonUtils
import com.example.common.vm.BaseViewModel
import com.example.login.intent.LoginViewIntent
import com.example.login.model.LoginRepository
import com.example.login.state.LoginUiState
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.Dispatcher
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: LoginRepository):BaseViewModel<LoginViewIntent>(){
   private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.NoneState)
    val uiState:StateFlow<LoginUiState> = _uiState.asStateFlow()
   override fun dispatchIntent(intent: LoginViewIntent) {
            when(intent){
                is LoginViewIntent.LoginToServer -> loginToServer(intent.password,intent.username)
                else ->{}
            }
    }

    private fun loginToServer(password: String, username: String) {
        viewModelScope.launch(Dispatchers.IO){
            try {
                var resultData = repository.loginToServer(password,username)
                if(resultData.code == 0){
                    MMKV.defaultMMKV().encode("token",resultData.data.token)
                    _uiState.value = LoginUiState.LoginSuccess(resultData.data)
                }else{
                    _uiState.value = LoginUiState.LoginFailure(resultData.msg)
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = LoginUiState.LoginFailure(e.message?:"接口异常")
            }finally {
                cancel()
            }
        }
    }
}